package com.i2863.receipt.controller;

import com.i2863.receipt.entity.Account;
import com.i2863.receipt.entity.Site;
import com.i2863.receipt.service.AccountService;
import com.i2863.receipt.service.SiteService;
import com.i2863.receipt.userUtil.User;
import com.i2863.receipt.userUtil.UserCenter;
import com.i2863.receipt.userUtil.UserException;
import com.i2863.receipt.util.ResultJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/6/8.
 */
@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    private static int PAGESIZE = 10;

    /**
     *
     * @param modelMap
     * @param queryContent 查询关键字
     * @param pageNum 页码
     * @return
     */
    @RequestMapping("/getlist")
    public String getList(ModelMap modelMap,
                          @RequestParam(value = "queryContent",required = false)String queryContent,
                          @RequestParam(value = "pageNum",required = false,defaultValue = "1")Integer pageNum){
        HttpSession session = request.getSession();
        Integer siteId = (Integer) session.getAttribute("siteId");
        Page<Account> page = accountService.queryByPage(PAGESIZE,pageNum,queryContent,siteId);
        List<Account> list = page.getContent();
        final Map<String,User> userMap = new HashMap<String,User>();
        for (Account account : list) {
            userMap.put(account.getUsername(),new User(account.getUsername()));
        }
        //从用户中心获取昵称和站点id
        UserCenter.loadUserInfo(userMap);
        for (int i = 0; i<list.size() ; i++) {
            User user = userMap.get(list.get(i).getUsername());
            list.get(i).setNickName(user.getNickName());
        }
        modelMap.put("list",list);
        modelMap.put("total",page.getTotalElements());
        modelMap.put("pageNum",pageNum);
        modelMap.put("pageSize",PAGESIZE);
        modelMap.put("queryContent",queryContent);
        return "account/list";
    }

    /**
     * 跳转添加页面
     * @return
     */
    @RequestMapping("/toadd")
    public String add(){
        return "account/add";
    }

    /**
     * 跳转编辑页面
     * @param accountId
     * @param modelMap
     * @return
     */
    @RequestMapping("/toedit")
    public String edit(Integer accountId,ModelMap modelMap){
        Account account = accountService.findOne(accountId);
        modelMap.put("account",account);
        return "account/edit";
    }

    /**
     * 新增一条记录
     * @param account
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public String save(Account account){
        HttpSession session = request.getSession();
        Integer siteId = (Integer) session.getAttribute("siteId");
        Site site = siteService.findOne(siteId);
        if(site==null){
            //从配置系统获取站点信息  并且在站点表新建一条记录
            Site entity = siteService.findBySiteId(siteId);
            entity.setCreateDate(new Date());
            entity.setModifyDate(new Date());
            siteService.add(entity);
        }
        account.setSite(siteService.findOne(siteId));
        accountService.add(account);
        return ResultJson.successMeg("添加成功");
    }

    /**
     * 修该一条记录
     * @param account
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(Account account){
        Integer id = account.getId();
        Account entity = accountService.findOne(id);
        entity.setRole(account.getRole());
        accountService.update(entity);
        return  ResultJson.successMeg("修改成功");
    }

    /**
     * 用户名验证
     * @param username
     * @return
     */
    @RequestMapping(value = "exusername",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String exusername(String username){
        username = username.trim();
        //从数据库查询以用户名查询
        Account account = accountService.findByUsername(username);
        if(account!=null){
            return ResultJson.errorMes("该用户名已存在");//已存在的用户
        }

        try {
            User user = UserCenter.getUserByName(username);
            return ResultJson.successResult("可以使用的用户名",user);
        }catch (UserException e){
            return ResultJson.errorMes("用户名验证异常，请稍后访问");
        }catch (RuntimeException e){
            return ResultJson.errorMes("用户名不存在");//用户中心里找不到该用户
        }
    }

    /**
     * 删除（批量）
     * @param ids
     * @return
     */
    @RequestMapping("/del")
    @ResponseBody
    public String del(@RequestParam(value = "ids")String ids){
        String[] idArray = ids.split(",");
        for (String id:idArray){
            accountService.del(Integer.parseInt(id));
        }
        return ResultJson.successMeg("删除成功");
    }


}
